package com.gollum.mq;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gollum.common.domain.redis.MqMessage;
import com.gollum.common.exception.MqException;
import com.gollum.common.utils.SpringUtils;
import com.gollum.common.utils.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.stream.ObjectRecord;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * 消息发送
 *
 * @author Herther
 * @createTime 2022年11月02日 23:46:00
 * @since 1.0.0
 */
@Component
public class MqSender {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ObjectMapper objectMapper;


    public <T> void send(String queueName, T object)  {
        if (Objects.isNull(object)){
            throw new MqException("不能发送空的消息");
        }
        try {
            MqMessage<T> redisMessage = new MqMessage<>();
            redisMessage.setQueueName(queueName)
                    .setCreateTime(new Date())
                    .setData(object)
                    .setMsg("TEST");
            //String jsonMessage = JSONUtil.toJsonStr(redisMessage);
            String jsonMessage = objectMapper.writeValueAsString(redisMessage);
            //构造消息
            ObjectRecord<String, String> message = StreamRecords.objectBacked(jsonMessage)
                    .withStreamKey(queueName);
            //发送消息
            redisCache.addStreamMsg(message);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
